import Response from '../../utils/response.js';
import { shjApi } from '../../utils/request.js';

// 获取水质断面列表
export const getList = async (ctx) => {
  try {
    // 创建参数对象
    const params = new URLSearchParams();
    
    // 添加默认参数
    params.append('dataType', 'month');
    
    const isTotal = ctx.request.body.isTotal;
    const queryName = ctx.request.body.name;
    const queryArea = ctx.request.body.area;
    const queryTown = ctx.request.body.town;
    
    if (queryName) {
      params.append('name', queryName);
    }

    if (queryArea) {
      params.append('areaCode', queryArea);
    }

    if (queryTown) {
      params.append('townCode', queryTown);
    }

    const response = await shjApi.post('/shuihuanjing/section/statistics/layering/info', params, {
      headers: {
        token: ctx.headers.token,
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });

    if (response.data) {
        const { code, data } = response.data
        // 确保content和list有默认值
        const safeContent = data || {}
        const list = safeContent || []
        const totalCount = safeContent.length || 0
        
        if (code == '0000') {
          const statusCount = {
            '全部': totalCount,
            '正常': 0,
            '数据延迟': 0,
            '数据缺失': 0,
            '延迟1个月': 0,
            '延迟3个月': 0,
            '延迟6个月以上': 0
          };
          
          const mappedList = list.map(item => {
            const dataMonitorTime = item.dataTime;

            // 设置状态
            let status;

            try {
              // 尝试解析监测时间，如果解析失败则使用当前时间
              // 检查是否为有效日期
              if (dataMonitorTime === null || dataMonitorTime === '' || dataMonitorTime === undefined) {
                status = '数据缺失';
              } else {
                let filterDataMonitorTime = `${dataMonitorTime.replace(/-/g, '/')}/01`;
                const monitorTime = dataMonitorTime ? new Date(filterDataMonitorTime) : new Date();
                // 计算时间差（毫秒）

                // 计算当前时间与 filterDataMonitorTime 相差多少个月
                const currentDate = new Date();
                const yearDifference = currentDate.getFullYear() - monitorTime.getFullYear();
                const monthDifference = currentDate.getMonth() - monitorTime.getMonth();
                const totalMonthDifference = yearDifference * 12 + monthDifference;

                if (totalMonthDifference <= 1) {
                  status = '正常';
                }
                if (totalMonthDifference > 1) {
                  status = '延迟1个月';
                }  
                if (totalMonthDifference > 3) {
                  status = '延迟3个月';
                } 
                if (totalMonthDifference > 6) { 
                  status = '延迟6个月以上';
                }
              }
            } catch (error) {
              console.error('解析时间错误:', error);
              status = '数据缺失';
            }

            // 更新状态计数
            statusCount[status] = (statusCount[status] || 0) + 1;
            statusCount['数据延迟'] = statusCount['全部'] - statusCount['正常'] - statusCount['数据缺失']
            
            return {
              ...item,
              status
            };
          });

          const resObj = { statusCount }
                    
          if (isTotal == '0') {
            resObj.list = mappedList
          }

          ctx.body = Response.success(resObj)
        } else {
          ctx.body = Response.error('获取数据失败')
        }
    } else {
      console.error('获取数据失败:');
      ctx.body = Response.error('获取数据失败');
    }
  } catch (err) {
    console.error('请求失败:', err);
    ctx.body = Response.error('获取数据失败')
  }
};
